package com.tanhua.admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tanhua.commons.Constants;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 分页查询用户
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult<UserInfoVoAge> findUserPage(Long page, Long pageSize) {
        PageResult<UserInfo> pageResult = userInfoApi.findPage(page, pageSize);
        List<UserInfo> userInfos = pageResult.getItems();
        List<UserInfoVoAge> vos = userInfos.stream().map(u -> {
            UserInfoVoAge userInfoVoAge = new UserInfoVoAge();
            BeanUtils.copyProperties(u, userInfoVoAge);
            String key = Constants.FREEZE_USER + u.getId();
            if (stringRedisTemplate.hasKey(key)) {
                userInfoVoAge.setUserStatus("2");
            }
            return userInfoVoAge;
        }).collect(Collectors.toList());

        return new PageResult<>(page, pageSize, pageResult.getCounts(),vos);
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    public UserInfoVoAge findById(Long userId) {
        UserInfo userInfo = userInfoApi.getById(userId);
        UserInfoVoAge userInfoVoAge = new UserInfoVoAge();
        BeanUtils.copyProperties(userInfo, userInfoVoAge);

        String key = Constants.FREEZE_USER + userId;
        if (stringRedisTemplate.hasKey(key)) {
            userInfoVoAge.setUserStatus("2");
        }
        userInfoVoAge.setCreated(userInfo.getCreated().getTime());

        return userInfoVoAge;
    }

    /**
     * 查询指定用户发布的所有视频列表
     * @param page
     * @param pageSize
     * @param uid
     * @return
     */
    public PageResult findAllVideos(Long page, Long pageSize, Long uid) {
        PageResult<Video> pageResult = videoApi.getByUserId(uid, page, pageSize);
        List<Video> videos = pageResult.getItems();
        List<VideoVo> vos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(videos)) {
            List<Long> userIds = videos.stream().map(Video::getUserId).collect(Collectors.toList());
            Map<Long, UserInfo> userInfoMap = userInfoApi.getBatchIdsByCondition(userIds, null);
            vos = videos.stream().map(video -> {
                UserInfo userInfo = userInfoMap.get(video.getUserId());
                return VideoVo.init(userInfo, video);
            }).collect(Collectors.toList());
        }

        return new PageResult(page, pageSize, pageResult.getCounts(), vos);
    }

    /**
     * 查询个人动态
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    public PageResult findAllMovements(Long page, Long pagesize, Long uid, Integer state) {
        PageResult<Movement> pageResult = movementApi.getMovementsByCondition(uid, state, page, pagesize);
        List<MovementsVo> vos = new ArrayList<>();
        List<Movement> movements = pageResult.getItems();
        if(CollectionUtils.isEmpty(movements)) {
            return new PageResult(page, pagesize, pageResult.getCounts(), vos);
        }

        List<Long> userIds = movements.stream().map(Movement::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> userInfoMap = userInfoApi.getBatchIdsByCondition(userIds, null);
        vos = movements.stream().map(movement -> MovementsVo.init(userInfoMap.get(movement.getUserId()), movement)).collect(Collectors.toList());
        return new PageResult(page, pagesize, pageResult.getCounts(), vos);
    }

    /**
     * 用户冻结
     * @param params
     * @return
     */
    public Map<String, String> userFreeze(Map<String, String> params) {
        Long userId = Long.valueOf(params.get("userId"));
        String key = Constants.FREEZE_USER + userId;
        Integer freezingTime = Integer.valueOf(params.get("freezingTime"));
        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();
        String redisJSON = JSON.toJSONString(params);
        switch (freezingTime) {
            case 1:
                redis.set(key, redisJSON, 3L, TimeUnit.DAYS);
                break;
            case 2:
                redis.set(key, redisJSON, 7L, TimeUnit.DAYS);
                break;
            case 3:
                redis.set(key, redisJSON);
                break;
            default:
                break;
        }
        //TODO 保存数据库

        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("message", "冻结成功");
        return resultMap;
    }


    /**
     * 用户解冻
     * @param userId
     * @param reasonForThawing
     * @return
     */
    public Map<String, String> unfreezeUser(Long userId, String reasonForThawing) {
        String key = Constants.FREEZE_USER + userId;
        stringRedisTemplate.delete(key);

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("message","解冻成功");
        return resultMap;
    }

    /**
     * 动态详情
     * @param id
     * @return
     */
    public MovementsVo movementDetail(String id) {
        Movement movement = movementApi.getMovementById(id);
        UserInfo userInfo = userInfoApi.getById(movement.getUserId());
        Integer likeCount = commentApi.findLikeCount(id);
        Integer commentCount = commentApi.findCommentCount(id);

        MovementsVo vo = MovementsVo.init(userInfo, movement);
        vo.setLikeCount(likeCount);
        vo.setCommentCount(commentCount);
        return vo;
    }

    /**
     * 分页查询评论
     * @param messageID
     * @return
     */
    public PageResult getComment(String messageID, Long page, Long pageSize) {
        PageResult<Comment> pageResult = commentApi.pageCommentList(messageID, page, pageSize);
        List<Comment> comments = pageResult.getItems();
        List<CommentVo> vos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(comments)) {
            List<Long> userIds = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
            Map<Long, UserInfo> userInfoMap = userInfoApi.getBatchIdsByCondition(userIds, null);
            vos = comments.stream().map(comment -> {
                UserInfo userInfo = userInfoMap.get(comment.getUserId());
                return CommentVo.init(userInfo, comment);
            }).collect(Collectors.toList());
        }
        return new PageResult(page, pageSize, pageResult.getCounts(), vos);
    }

    /**
     * 动态通过
     * @param movementIds
     * @return
     */
    public Map<String, String> passMovement(List<ObjectId> movementIds) {
        Map<String, String> resultMap = new HashMap<>();
        int count = movementApi.audit(movementIds, 1);
        if(count > 0) {
            resultMap.put("message", "已通过" + count + "条动态");
        }
        return resultMap;
    }

    /**
     * 动态驳回
     * @param movementIds
     * @return
     */
    public Map<String, String> rejectMovement(List<ObjectId> movementIds) {
        Map<String, String> resultMap = new HashMap<>();
        int count = movementApi.audit(movementIds, 2);
        if(count > 0) {
            resultMap.put("message", "已驳回" + count + "条动态");
        }
        return resultMap;
    }


}
